import { defineComponent } from "vue";
import type { IChapter, ICourse } from '@/types'
import { useStore } from '@/hooks'
import { useRoute, useRouter } from "vue-router";
import styles from './index.module.less'
import { ElButton } from "element-plus";

export default defineComponent({
    name: 'Detail',
    setup() {
        const route = useRoute()
        const router = useRouter()
        const { courses, getCourse } = useStore()
        const course = getCourse(route.query.id as string)

        const openChapter = (chapter: IChapter) => {
            if (!chapter.questions.length) return

            router.push({
                path: 'detail',
                query: {
                    courseId: route.query.id,
                    chapterId: chapter.title
                }
            })
        }

        const renderChapter = (chapter: IChapter, index: number) => {
            if (!course) return
            const className = {
                [styles.courseItem]: true,
                disabled: chapter.questions.length === 0,
                'un-answered': index === 0,
                error: index === 1,
            }

            return (
                <div
                    class={className}
                    onClick={() => openChapter(chapter)}
                >
                    <div>
                        <div class={styles.courseItemTitle}>{chapter.title}</div>
                        <div>题目 {chapter.questions.length}个</div>
                    </div>
                </div>
            )
        }

        const renderContent = (chapters: IChapter[]) => {
            return (
                <div class={styles.courseContent}>
                    {chapters.map(renderChapter)}
                </div>
            )
        }


        return () => {
            if (!course) return
            return (
                <>
                    <ElButton onClick={() => router.push({ path: '/' })}>回到首页</ElButton>
                    <div class={styles.course}>
                        <div>{course.title}</div>
                        {renderContent(course.chapters)}
                    </div>
                </>
            )
        }
    }
})